package com.bluishoul.action;

import java.io.IOException;

import my.mvc.ActionException;
import my.mvc.Annotation.JSONOutputEnabled;
import my.mvc.RequestContext;

import org.apache.commons.lang.StringUtils;

import com.bluishoul.bean.Shop;
import com.google.gson.Gson;

public class ShopAction {
	
	@JSONOutputEnabled
	public void update(RequestContext rc) throws IOException{
		Shop shop = rc.form(Shop.class);
		_checkShopInfo(rc,shop);
		if(shop.getId()==0L)
			shop.Save();
		else{
			if(shop.Get(shop.getId())!=null)
				shop.Update();
			else
				throw rc.error("shop_not_exist");
		}
		rc.print(new Gson().toJson(shop));
	}
	
	private static void _checkShopInfo(RequestContext rc,Shop shop) throws ActionException{
		if(shop==null)
			throw rc.error("shop_not_null");
		if(StringUtils.isBlank(shop.getName()))
			throw rc.error("shop_name_not_empty");
		if(StringUtils.isBlank(shop.getAddr_prv()) && StringUtils.isBlank(shop.getAddr_city()) && StringUtils.isBlank(shop.getAddr_city()))
			throw rc.error("shop_addr_required_null");
		if(StringUtils.isBlank(shop.getTel()))
			throw rc.error("shop_tel_not_empty");
		Shop ex = shop.hasSame();
		if(ex!=null)
			throw rc.error("shop_exist",ex.getId(),ex.getName());
	}
}
